/**
 * Created by linxiao on 2016/8/26.
 */
function TtqIndex(ui) {
    this.ui = ui;
    this.domReady();
    $("#edui31_body").trigger("click");
    //new Select()
};

TtqIndex.prototype.domReady = function () {
    var ui = this.ui;
    var index = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
    var thisObj = this;
    var topicId = $("input[name=topicId]").val();
    var initKStatus = $("input[name=initKStatus]").val();
    $.ajax({
        url: HOST+"/index/Bxbl/ttqGetQuestion",
        data:{
            topicId: topicId
        },
        type:'POST',
        dataType:'json',
        success: function(response){
            if(response.is_end==0){
                if(!MY_UI.isEmpty(response.question_list))
                {
                    var sheetArea = "";
                    if(response.question_list.q_type == 1){
                        sheetArea += thisObj.initQuestionOption(response);
                    }else{
                        sheetArea += thisObj.initQuestionInput(response);
                    }
                    sheetArea +=thisObj.initSubmitButton();
                    //$("#qu-list").html(thisObj.questionList(response));
                    $("#analyze-sheet-area").html(thisObj.initQuestionAnalyzeTitle(response));
                    $("#sheet-area").html(sheetArea);
                    $(".payment-wizard").html(thisObj.initAnalyzeArea(response));
                    $("#doc-oc-demo3").find("#adic").click(function () {
                        $("#doc-oc-demo3").offCanvas('close');
                    });
                    //$("#doc-video").html(thisObj.initVideo(response));
                    //var myPlayer =  _V_('example_video_1');  //初始化视频
                    //myPlayer.src(response.tag_video);  //重置video的src
                    //myPlayer.load(response.tag_video);  //使video重新加载
                    //$('.cd-close').on('click', function (event) {
                    //    myPlayer.pause();
                    //});
                    $("#tag-slider").html(thisObj.initTagNameList(response));
                    $("#recommended").html(initTagNameLists());
                    $("#tagTames").html(thisObj.initTagName(response));
                    $('.am-slider').flexslider({itemWidth: 245, itemMargin: 3, slideshow: false});
                    //$(".doc-modal").trigger("click");
                    var myPlayer = _V_('example_video_1');  //初始化视频
                    myPlayer.src(response.tag_video);  //重置video的src
                    myPlayer.load(response.tag_video);  //使video重新加载
                    $('.cd-close').on('click', function (event) {
                        myPlayer.pause();
                    });
                    //var knowledgeQuestion=$('#knowledgeQuestion').val();
                    //knowledgeQuestion=eval('('+knowledgeQuestion+')');
                    //console.log(knowledgeQuestion);
                    //var knowledgeQuestion_html='';
                    //for(i in knowledgeQuestion){
                    //    knowledgeQuestion_html+=knowledgeQuestion[i].knowlegecode.name+'  ';
                    //    console.log(knowledgeQuestion_html);
                    //    $("#recommended").html("知识点："+knowledgeQuestion_html+"<br/>")
                    //    knowledgeQuestion_html+='答题数量'+knowledgeQuestion[i].count+'道\n';
                    //}
                    $(".done").click(function(){
                        var this_li_ind = $(this).parent().parent("li").index();
                        if($('.payment-wizard li').hasClass("jump-here")){
                            $(this).parent().parent("li").removeClass("active").addClass("completed");
                            $(this).parent(".wizard-content").slideUp();
                            $('.payment-wizard li.jump-here').removeClass("jump-here");
                        }else{
                            $(this).parent().parent("li").removeClass("active").addClass("completed");
                            $(this).parent(".wizard-content").slideUp();
                            $(this).parent().parent("li").next("li:not('.completed')").addClass('active').children('.wizard-content').slideDown();
                        }
                    });
                    $('.payment-wizard li .wizard-heading').click(function(){
                        if($(this).parent().hasClass('completed')){
                            var this_li_ind = $(this).parent("li").index();
                            var li_ind = $('.payment-wizard li.active').index();
                            if(this_li_ind < li_ind){
                                $('.payment-wizard li.active').addClass("jump-here");
                            }
                            $(this).parent().addClass('active').removeClass('completed');
                            $(this).siblings('.wizard-content').slideDown();
                        }
                    });
                    /*选项*/
                    $(".rdolist").labelauty("rdolist", "rdo");
                    //tijiao
                    $('.continue-topic',ui).click(function(){
                        $(".yx-xz").fadeOut();
                        var answer_val = "",question_type="",question_id="",answer_url="";
                        var topicId = $("input[name=topicId]").val();
                        var answer_content = [];
                        question_type = $(".question-sheet").data("type");
                        question_id = $(".question-sheet").data("question_id");
                        if(response.question_list.q_type == 1){

                            answer_val = $("label.checked").data("value");
                            answer_val  = answer_val==undefined ? '' : answer_val;
                            question_id = question_id==undefined ? '' : question_id;
                            answer_url = "";
                            question_type = question_type==undefined ? '' : question_type;
                        }else if(response.question_list.q_type == 2){
                            var input_answer_val = '',input_answer_base64 = '';
                            //question_id = $(".input-p").attr('data-question_id');
                            //question_type = $(".input-p").attr('data-type');
                            $("div[class='input-p']").each(function(i,qv){
                                if($(qv).find("img").length>0){
                                    $(qv).find("img").each(function(ii,v){
                                        input_answer_base64 = v.getAttribute("src");
                                        input_answer_val = v.getAttribute("data-latex");
                                        input_answer_val  = input_answer_val==undefined ? '' : input_answer_val;
                                        input_answer_base64 = input_answer_base64==undefined ? '' : input_answer_base64;
                                    });
                                    if(i>0 && !MY_UI.isEmpty(input_answer_val)) {
                                        input_answer_val += ";"+input_answer_val;
                                        input_answer_base64 += "@@@"+input_answer_base64;
                                    }
                                    answer_url = input_answer_base64;
                                    answer_val = input_answer_val;
                                }else{
                                    answer_val  = "";
                                    answer_url = "";
                                }
                            });
                        }
                        console.log(answer_val);
                        //return false;
                        if(MY_UI.isEmpty(answer_val)||answer_val=='\\placeholder '){
                            layer.confirm('您是答案为空，是否确认提交？', {
                                btn: ['是的','取消'] ,//按钮
                                shift:3
                            }, function(index){
                                layer.close(index);
                                $('.continue-topic',ui).unbind("click");
                                answer_content.push({question_id:question_id,answer_base64:answer_url,type:question_type,answer:answer_val});
                                thisObj.initSubmit(topicId,answer_content);
                            }, function(index){
                                layer.close(index);
                            });
                        }else{
                            answer_content.push({question_id:question_id,type:question_type,answer_base64:answer_url,answer:answer_val});
                            thisObj.initSubmit(topicId,answer_content);
                        }

                    });
                }else{
                    thisObj.domReady();
                }
            }else if(response.is_end==1){
                window.open(HOST+"index/Bxbl/ttqReport/topicId/"+topicId,"_self");
            }
        },
        complete:function(){
            layer.close(index);
        }
    });
}
/*
 * 初始化题目标题
 */
TtqIndex.prototype.initQuestionTitle = function (param) {
    var title = "<div class='question-sheet question-analysis'>"+param.question_list.content+"</div>"
        +"<div style='color: red'>这是测试内容："+param.question_list.id+"&nbsp;知识点标签tag_code:"+param.tag_code+"&nbsp;知识点难度:"+param.question_list.difficulty+"</div>";
    return title;
}
/*
 * 初始化题目填空
 */
TtqIndex.prototype.initQuestionInput = function (param) {
    var content = "";
    var question_content =MY_UI.htmlspecialcharsDecode(param.question_list.content);
    var n =(question_content.length-question_content.replace(/##\$\$##/g, "").length)/6;
    if(n>0){
        for(var i= 0;i < n;i++){
            content += question_content.split("##$$##")[i]+'<div onClick="showMathEdit(this)" data-num="input'+i+'" data-type="'+param.question_list.q_type+'" data-question_id="'+param.question_list.id+'" id="textarea" class="input-p" style="min-height:45px;border-bottom: 1px solid #000;"></div>';
        }
        content+=question_content.split("##$$##")[n];
    }else{
        content = MY_UI.htmlspecialcharsDecode(param.question_list.content);
    }

    var title = "<div class='question-sheet' data-type='"+param.question_list.q_type+"' data-question_id='"+param.question_list.id+"'>"+content+"</div>"
        //+"<div style='color: red'>这是测试内容："+param.question_list.id+"&nbsp;知识点标签tag_code:"+param.tag_code+"&nbsp;知识点难度:"+param.question_list.difficulty+"&nbsp;答案："+param.question_list.answer+"</div>";

    return title;
}
/*
 * 初始化题目选项
 */
TtqIndex.prototype.initQuestionOption = function (param) {
    var title = "<div class='question-sheet' data-type='"+param.question_list.q_type+"' data-question_id='"+param.question_list.id+"'>"+MY_UI.htmlspecialcharsDecode(param.question_list.content)+"</div>"
        //+"<div style='color: red'>这是测试内容："+param.question_list.id+"&nbsp;知识点标签tag_code:"+param.tag_code+"&nbsp;知识点难度:"+param.question_list.difficulty+"</div>";
    var option = '',optionChild = "";
    var optionNum = param.question_list.options;
    for(var i = 0;i< optionNum.length;i++){
        optionChild += '<input type="radio" name="rdo" class="rdolist"/>'
            + '<label data-type="'+param.question_list.q_type+'" data-question_id="'+param.question_list.id+'" data-value="'+param.question_list.options[i].key+'" class="rdobox">'
            + '<span class="radiobox-content">'+param.question_list.options[i].key+'、'+MY_UI.htmlspecialcharsDecode(param.question_list.options[i].content)+'</span>'
            + '</label>';
    }
    option = '<div class="rdo" data-type="'+param.question_list.q_type+'" data-question_id="'+param.question_list.id+'">'+optionChild+'</div>';
    return title+option;
}
/*
 * 初始化解析题目内容
 */
TtqIndex.prototype.initQuestionAnalyzeTitle = function (param) {
    var content = "";
    var question_content =MY_UI.htmlspecialcharsDecode(param.question_list.content);
    var n =(question_content.length-question_content.replace(/##\$\$##/g, "").length)/6;
    if(n>0){
        for(var i= 0;i < n;i++){
            content += question_content.split("##$$##")[i]+'<div style="cursor:pointer;min-height:90px;border-bottom: 1px solid #000;background: #FFFFFF;"></div>';
        }
        content += question_content.split("##$$##")[n];
        content+='<div class="answer" style="font-size:1.2em;color:#000;margin-top:20px;display: none;">'+'参考答案：'+'<img src="'+param.question_list.answer_base64[0]+'">'+'</div>';
    }else{
        var option = '',optionChild = "";
        var optionNum = param.question_list.options;
        for(var i = 0;i< optionNum.length;i++){
            optionChild += '<label data-type="'+param.question_list.q_type+'" data-question_id="'+param.question_list.id+'" data-value="'+param.question_list.options[i].key+'" class="rdobox">'
                + '<span class="radiobox-content">'+param.question_list.options[i].key+'、'+MY_UI.htmlspecialcharsDecode(param.question_list.options[i].content)+'</span>'
                + '</label>';
        }
        option = '<div class="rdo" data-type="'+param.question_list.q_type+'" data-question_id="'+param.question_list.id+'">'+optionChild+'</div>';
        content = MY_UI.htmlspecialcharsDecode(param.question_list.content)+option+'<div class="answer" style="font-size:1.2em;color:#000;margin-top:20px;display: none;">'+'参考答案：'+param.question_list.answer[0]+'</div>';

    }

    var title = "<div class='question-sheet question-analysis'>" +
        "<span class='am-badge am-badge-danger am-text-xl'>题目：</span>"
        +content+"</div>";

    return title;
}
/*
 * 创建提交按钮
 */
TtqIndex.prototype.initAnalyzeArea = function (param) {
    var analyze = param.question_list.analyze[0].content;
    var analyzeContent = '<li class="active"><div class="wizard-heading"><span class="icon-mode"></span></div><div class="wizard-content">'+
        '<p>'+MY_UI.htmlspecialcharsDecode(param.question_list.analyze[0].title)+'</p><button class="btn-green done" type="submit">下一步</button></div></li>';
    for(var i=0;i<analyze.length;i++){
        if(i==(analyze.length-1)){
            analyzeContent += '<li><div class="wizard-heading"><span class="icon-mode"></span></div><div class="wizard-content">'+
                '<p>'+MY_UI.htmlspecialcharsDecode(analyze[i].content)+'</p><button class="btn-green" id="findAnswer"  type="submit">查看答案</button><button style="display:none" class="btn-green" id="continue"  type="submit">继续</button></div></li>';
        }else{
            analyzeContent += '<li><div class="wizard-heading"><span class="icon-mode"></span></div><div class="wizard-content">'+
                '<p>'+MY_UI.htmlspecialcharsDecode(analyze[i].content)+'</p><button class="btn-green done" type="submit">下一步</button></div></li>';
        }
    }
    return analyzeContent;
}

/*
 * 创建提交按钮
 */
TtqIndex.prototype.initSubmitButton = function () {
    var submitButton = '<div class="amz-toolbar" id="amz-toolbar"><div class="continue-topic"></div></div>';
    return submitButton;
}
/*
 * 提交操作
 */
TtqIndex.prototype.initSubmit = function (topicId,answer_content) {
    var index = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
    var thisObj = this;
    $.ajax({
        url: HOST+"/index/Bxbl/ttqSubmitQuestion",
        data:{
            topicId: topicId,
            answer_content: answer_content
        },
        type:'POST',
        dataType:'json',
        success: function(response){
            var timer = "";
            if(response.isSuccess==1){
                if(response.is_right==1){
                    var $btns = $('#animation-group').find('.right');
                    var dfds = [];
                    var animating = false;
                    var animation = 'am-animation-scale-up';
                    $btns.css("display","block");
                    if (!animating) {
                        animating = true;
                        $btns.each(function() {
                            var dfd = new $.Deferred();
                            dfds.push(dfd);
                            var $this = $(this);
                            if ($.AMUI.support.animation) {
                                $this.addClass(animation).one($.AMUI.support.animation.end, function() {
                                    $this.removeClass(animation);
                                    dfd.resolve();
                                });
                            }
                        });

                        $.when.apply(null, dfds).done(function() {
                            animating = false;
                            console.log('[AMUI] - 所有动画执行完成');
                            timer=setTimeout(function(){
                                $btns.css("display","none");
                                thisObj.domReady();
                            }, 2000);
                            dfds = [];
                        });
                    }
                }else{
                    var $btns = $('#animation-group').find('.error');
                    var dfds = [];
                    var animating = false;
                    var animation = 'am-animation-scale-up';
                    $btns.css("display","block");
                    if (!animating) {
                        animating = true;
                        $btns.each(function() {
                            var dfd = new $.Deferred();
                            dfds.push(dfd);
                            var $this = $(this);
                            if ($.AMUI.support.animation) {
                                $this.addClass(animation).one($.AMUI.support.animation.end, function() {
                                    $this.removeClass(animation);
                                    dfd.resolve();
                                });
                            }
                        });

                        $.when.apply(null, dfds).done(function() {
                            animating = false;
                            console.log('[AMUI] - 所有动画执行完成');
                            timer=setTimeout(function(){
                                $btns.css("display","none");
                                $(".detail-left").css({left:"0",top:"95px"}).stop(true,true).animate({left:0,top:"95px"},8000);
                                $("#amz-toolbar").css("display","none");
                                $(".payment-wizard").find("#findAnswer").click(function(){
                                    $(".question-sheet").find(".answer").show();
                                    $("#findAnswer").hide();
                                    $("#continue").show();
                                    $("#continue").on("click",function(){
                                        $(".detail-left").css({left:"-75%",top:"-750px"}).stop(true,true).animate({left:"-75%",top:"-750px"},800);
                                        thisObj.domReady();
                                    });
                                });
                            }, 2000);
                            dfds = [];
                        });
                    }
                }
            }else {
                console.log(response.error)
            }
        },
        complete:function(){
            layer.close(index);
        }
    });
}
/*
 * 初始化知识点列表
 */
TtqIndex.prototype.initTagNameList = function (param) {
    var tagList = "";
    var tagListLength = param.tag_code_timeline.length;
    localStorage.setItem("tagListLength",tagListLength)
    for(var i = 0;i< tagListLength;i++){
        tagList += '<li class="am-img-thumbnail tag-name" >'+param.tag_code_timeline[i].tag_name+'</li>';
    }
    //for(var i = 0;i< 3;i++){
    //    tagList += '<li class="am-img-thumbnail tag-name" >'+param.tag_code_timeline[0].tag_name+'</li>';
    //}
    return tagList;
}

 function initTagNameLists (){
    var knowledgeQuestion=$('#knowledgeQuestion').val();
    knowledgeQuestion=eval('('+knowledgeQuestion+')');
    var knowledgeQuestion_html='';
    var tagList='';
    for(i in knowledgeQuestion){
        knowledgeQuestion_html+='<li class="am-u-lg-12">'+'知识点：'+knowledgeQuestion[i].knowlegecode.name+'；  '+'<span>'+'答题数量：'+knowledgeQuestion[i].count+'道\n'+'；'+'</span>'+'</li>';
    }
    return knowledgeQuestion_html+'<br/>'
}


TtqIndex.prototype.initTagName=function(param){
    console.log(param);
    return param.tag_name;
}

/*
 * 进度
 */
TtqIndex.prototype.questionList = function (param) {
    //console.log(param);
    var questionlength = param.has_answered_questions.length;
    //console.log(questionlength);
    var questionList = '<label style="float: right" for="" class=""></label>';
    for(var i=0;i<questionlength;i++){
        questionList += '<label style="float: right" for="" class="add"></label>';
    }
    return questionList;
}

//解析中的视频
TtqIndex.prototype.initVideo=function(param){
    console.log(param);
    var video= '<video id="example_video_1" class="video-js vjs-amazeui" controls preload="none" width="640" height="384" poster="src/images/bg.jpg" data-setup="{}">'+
        +'<source src="'+param.tag_video+'"type="video/mp4"/>'+
        '<source src="'+param.tag_video+'" type="video/webm"/>'+
        '<source src="'+param.tag_video+'" type="video/ogg"/>'+
        '<track kind="captions" src="video.js/demo.captions.vtt" srclang="en" label="English"></track>'+<!-- Tracks need an ending tag thanks to IE9 -->
        '<track kind="subtitles" src="video.js/demo.captions.vtt" srclang="en" label="English"></track>'+<!-- Tracks need an ending tag thanks to IE9 -->
        '<p class="vjs-no-js">To view this video please enable JavaScript, and consider upgrading to a web browser that <a href="http://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a></p>'+
        '</video>';
    return video;
    //return param.tag_video;
}
